#!/usr/bin/perl

use strict;

package MSAUtils;
use base qw(Exporter);

our @EXPORT_OK = qw(
        GetMsaForWwn
        GetWwnsForMsa
        GetMsaModels

    );

our %EXPORT_TAGS = (
    'all' => [@EXPORT_OK],
);

use Data::Dumper;

my %_cmds = (
    multipath => '/sbin/multipath',
    scsi_id => '/sbin/scsi_id',
    egrep => '/bin/egrep',
    sg_inq => '/usr/bin/sg_inq',
    lsscsi => '/usr/bin/lsscsi',
);

### msa parameters
{
  my %msas = ();      # a cache for msa instances

  my %_wwn_msa = () ; # map from wwn to msa
  sub GetMsaForWwn
  {
      my $wwn = $_[0];
      if (%_wwn_msa == 0) {
          chomp (my @allmsas = `$_cmds{egrep} -o msa[0-9]+ /etc/hosts`);
          @allmsas = keys %{{map { $_ => 1 } @allmsas}}; # remove duplicate

          foreach (@allmsas) {
              my $msa = $msas{$_} || Lunmgr::MSA->new($_);
              $msas{$_} = $msa;
              $_wwn_msa{$_} = $msa foreach ($msa->wwns);
          }
      }

      $_wwn_msa{$wwn};
  }

  my %_msa_wwns = () ; # map from wwn to msa
  sub GetWwnsForMsa
  {
      my @msas = @_;
      my @wwns = ();
      foreach (@msas) {
          unless ($_msa_wwns{$_}) {
              my $msa = $msas{$_} || Lunmgr::MSA->new($_);
              $msas{$_} = $msa;
              $_msa_wwns{$_} = [$msa->wwns];
          }
          push @wwns, @{$_msa_wwns{$_}};
      }
      return @wwns;
  }

  sub GetMsaModels
  {
    my @msas = @_;
    my %models = ();
    foreach (@msas) {
        my $msa = $msas{$_} || Lunmgr::MSA->new($_);
        $msas{$_} = $msa;

        my @keys = keys %{$msa->models};
        @models{keys %{$msa->models}} = values %{$msa->models};
    }

    return %models;
  }

}

1;
